import Vue from 'vue'
import Router from 'vue-router'

const Login = () => import(/* webpackChunkName: "login_home_wellcome" */ './components/Login.vue')
const Home = () => import(/* webpackChunkName: "login_home_wellcome" */ './components/Home.vue')
const Wellcome = () => import(/* webpackChunkName: "login_home_wellcome" */ './components/Wellcome.vue')

const Users = () => import(/* webpackChunkName: "users_rights_role" */ './components/users/Users.vue')
const RoleList = () => import(/* webpackChunkName: "users_rights_role" */ './components/power/RoleList.vue')
const Rights = () => import(/* webpackChunkName: "users_rights_role" */ './components/power/Rights.vue')

const Cate = () => import(/* webpackChunkName: "cate_params" */ './components/goods/Cate.vue')
const Params = () => import(/* webpackChunkName: "cate_params" */ './components/goods/Params.vue')

const Goods = () => import(/* webpackChunkName: "goods_add" */ './components/goods/Goods.vue')
const Add = () => import(/* webpackChunkName: "goods_add" */ './components/goods/Add.vue')

const Order = () => import(/* webpackChunkName: "order_report" */ './components/order/Order.vue')
const Report = () => import(/* webpackChunkName: "order_report" */ './components/report/Report.vue')

Vue.use(Router)

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location)
}

let router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/home',
      component: Home,
      redirect: '/wellcome',
      children: [
        {
          path: '/wellcome',
          component: Wellcome,
          beforeEnter: (to, from, next) => {
            window.sessionStorage.removeItem('activePath')
            next()
          }
        },
        { path: '/users', component: Users },
        { path: '/roles', component: RoleList },
        { path: '/rights', component: Rights },
        { path: '/categories', component: Cate },
        { path: '/params', component: Params },
        { path: '/goods', component: Goods },
        { path: '/goods/add', component: Add },
        { path: '/orders', component: Order },
        { path: '/reports', component: Report }
      ]
    }
  ]
})

// 验证是否登录的功能
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  let tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  // 代表已经登录
  next()
})

export default router
